//
//  FormatHelper.m
//  Feeder
//
//  Created by Diego Acosta on 9/5/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "FormatHelper.h"
#import "MREntitiesConverter.h"

#define kSecondsInADay 86400
#define kSecondsInAnHour 3600
#define kSecondsInAMinute 60


@implementation FormatHelper

#pragma mark -
#pragma mark Public methods

+ (NSString *)stringFormatForTitle:(NSString *)title withUnreadCount:(NSString *)count {

	NSMutableString * _title = [NSMutableString string];
	
	// add title.
	[_title appendFormat:@"%@", title];
	
	// add spacing and count if there's unread elements.
	if ([count length] > 0) {
		
		[_title appendFormat:@" (%@)", count];
	}
	
	return (NSString *)_title;
}

+ (NSString *)convertHTMLEntiesInString:(NSString *)text {

	// initialize HTML entities parser.
	MREntitiesConverter * parser = [[MREntitiesConverter alloc] init];
	
	return [parser convertEntiesInString:text];
}

+ (NSString *)removeHTMLTagsInString:(NSString *)html {
	
    NSScanner * scanner;
    NSString * text = nil;
	
    scanner = [NSScanner scannerWithString:html];
	
    while ([scanner isAtEnd] == NO) {
		
        // find start of tag
        [scanner scanUpToString:@"<" intoString:NULL] ; 
		
        // find end of tag
        [scanner scanUpToString:@">" intoString:&text] ;
		
        // replace the found tag with an empty character.
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text]
											   withString:@""];
    }
    
    return html;
}

+ (NSString *)removeConsecutiveSpacesInString:(NSString *)text {

	NSString * _text = [text copy];
	
	// create an array splitting words.
	NSCharacterSet * whitespaces = [NSCharacterSet whitespaceCharacterSet];
	NSArray * parts = [_text componentsSeparatedByCharactersInSet:whitespaces];
	
	// remove space chars from array using predicate.
	NSPredicate * noEmptyStrings = [NSPredicate predicateWithFormat:@"SELF != ''"];
	NSArray * filteredArray = [parts filteredArrayUsingPredicate:noEmptyStrings];
	
	// join string again
	_text = [filteredArray componentsJoinedByString:@" "];

	return _text;
}

+ (NSString *)feedDetailForString:(NSString *)html {

	NSString * text;
	
	// remove all the html tags.
	text = [self removeHTMLTagsInString:html];
	
	// convert html entities (e.g.: &amp).
	text = [self convertHTMLEntiesInString:text];
		
	// replace all new lines by spaces.
	text = [text stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	
	// remove consecutive spaces.
	text = [self removeConsecutiveSpacesInString:text];
	
	// truncate text since we're going to show only a few lines.
	if ([text length] > kFeedItemDetailCharCount) {
		
		text = [text substringToIndex:kFeedItemDetailCharCount];
	}

	return text;
}

+ (NSString *)feedDateFromUnixTime:(NSNumber *)timestamp {
	
	NSString * formattedDate = [NSString string];
	
	NSTimeInterval unixDate = [timestamp intValue];
	NSDate * date = [NSDate dateWithTimeIntervalSince1970:unixDate];
	NSDate * currentDate = [NSDate date];
	
	// check hours difference from now.
	NSTimeInterval hours = [currentDate timeIntervalSinceDate:date] / kSecondsInAnHour;
	
	// user difference to show proper data.
	if (hours > 24) {
		
		// show days difference.
		NSTimeInterval days = [currentDate timeIntervalSinceDate:date] / kSecondsInADay;
		
		// we've to round down the number.
		NSUInteger _days = lroundf(days);
		
		// formated date response.
		if (_days > 1) {
			
			formattedDate = [NSString stringWithFormat:@"%d days ago", _days];
		}
		else {
			
			formattedDate = @"1 day ago";
		}
	}
	else if (hours >= 1) {
		
		// we've to round down the number.
		NSUInteger _hours = lroundf(hours);
		
		// formated date response.
		if (_hours > 1) {
			
			formattedDate = [NSString stringWithFormat:@"%d hours ago", _hours];
		}
		else {
			
			formattedDate = @"1 hour ago";
		}
	}
	else if (hours < 1) {
		
		// show minutes difference.
		NSTimeInterval minutes = [currentDate timeIntervalSinceDate:date] / kSecondsInAMinute;
		
		// we've to round down the number.
		NSUInteger _minutes = lroundf(minutes);
		
		// formated date response.
		if (_minutes > 1) {
			
			formattedDate = [NSString stringWithFormat:@"%d minutes ago", _minutes];
		}
		else {
			
			formattedDate = @"1 minute ago";
		}
	}
	
	return formattedDate;
}

@end
